const {
  Movie,
  Sentence,
  Music
} = require('./classic.js');

const {
  flatten
} = require('lodash');

const { host } = require('../config/config.js');
class Art {

  constructor(art_id, type) {
    this.art_id = art_id;
    this.type = type;
  }

  async getDetail(uid) {
    const art = await Art.getData(this.art_id, this.type);
    if (!art) {
      throw new Error('搞鸡毛!')
    }
    const {
      Favor
    } = require('../models/favor.js');
    const like = await Favor.userLikeIt(this.art_id, this.type, uid);
    return {
      art,
      like_status: like
    }
  }

  static async getList(artInfoList) {
    const artInfoObj = {
      100: [],
      200: [],
      300: []
    };

    for (let artInfo of artInfoList) {
      artInfoObj[artInfo.type].push(artInfo.art_id);
    };

    const arts = [];
    for (let key in artInfoObj) {
      if (artInfoObj[key].length === 0) {
        continue;
      }
      Art._getListByType(artInfoObj[key], key);
      arts.push(await Art._getListByType(artInfoObj[key], key));
    };
    return flatten(arts);
  }
  static async _getListByType(ids, type) {
    let arts = [];
    const finder = {
      where: {
        id: {
          [Op.in]: ids
        }
      }
    };
    switch (type) {
      case 100:
        arts = await Movie.findAll(finder);
        break;
      case 200:
        arts = await Music.findAll(finder);
        break;
      case 300:
        arts = await Sentence.findAll(finder);
        break;
      case 400:
        arts = await Movie.findAll(finder);
        break;
    };
    return art;
  }

  static async getData(art_id, type) {
  let art = null;
  const finder = {
    where: {
      id: art_id
    }
  };
  switch (type) {
    case 100:
      art = await Movie.findOne(finder);
      break;
    case 200:
      art = await Music.findOne(finder);
      break;
    case 300:
      art = await Sentence.findOne(finder);
      break;
    case 400:
      const { Book } = require('./book.js');
      art = await Book.findOne(finder);
      if (!art) {
        art = await Book.create({
          id: art_id
        });
      }
      break;
    };
    
    if (art && art.image) {
      let imgUrl = art.dataValues.image;
      art.dataValues.image = host + imgUrl;
    }
  return art;
}
};

module.exports = {
  Art
}